<?php
class MissionAction extends CommonAction {
    /**
     * 任务信息 首页
     */
    public function index() {
        $this->display('index');
    }
    //添加页面
    public function add() {
        $missions = M('mission')->select();
        //dump($missions);
        //获取所有表单信息
        $forms = M('form')->select();
        $this->assign('forms', $forms);
        $this->display();
    }
    //查看页面
    public function find() {
        if (isset($_POST['record'])) { //前台有流水号传入即查询
            $record = $_POST['record'];
            $mission = M('mission')->where(array(
                'record' => $record
            ))->find(); //查询任务
            $schedules = M('schedule')->where(array(
                'mission_id' => $mission['id']
            ))->select(); //查看进度
            $User = M('user');
            foreach ($schedules as $k => $v) {
                $user = $User->where(array(
                    'id' => $schedules[$k]['user_id']
                ))->find();
                $schedules[$k]['userName'] = $user['nickname'];
            }
            $this->assign('mission', $mission);
            $this->assign('schedules', $schedules);
        }
        $this->display();
    }
    //获取表单的模型信息
    public function getForm() {
        $fid = $this->_post('fid'); //获取表单表的ID值
        //查询该表单的详细信息
        $Form = M('form');
        $res = $Form->where(array(
            'id' => $fid
        ))->find();
        $this->assign('form', $res);
        $this->assign('fid', $fid);
        $Field = M('field');
        $fields = $Field->where(array(
            'form_id' => $fid
        ))->select();
        //遍历该表单下所有字段数据 将获得的数据做出处理渲染到表单模块 以达到页面获取表单模块的目的
        foreach ($fields as $v) {
            $this->assign('field_' . $v['id'], fieldDispose($v));
        }
        if (!$res) {
            exit(json_encode(''));
        }
        //dump($res);exit;
        //取得表单的模块数据且渲染（ajax效果返回）
        $datas['temp'] = $this->fetch('', $res['template']);
        $datas['fid'] = $fid;
        echo json_encode($datas);
        //$this->ajaxReturn($this->fetch('',$res['template']));
        
    }
    //通用文件上传
    public function _upload($file = 'file') {
        import("ORG.Net.UploadFile");
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize = 3 * 1024 * 1024;
        $upload->allowExts = explode(',', C('UPLOAD_EXTS'));
        $upload->savePath = "./Public/Uploads/" . __SITEID__ . '/' . MODULE_NAME . "" . __SITEID__ . "-";
        //自动命名
        $upload->saveRule = 'uniqid';
        //创建目录
        $upload->savePath = $upload->savePath . date('Ymd', time()) . "/";
        if (!file_exists("$upload->savePath")) {
            mk_dir($upload->savePath);
        }
        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = 0;
        //设置需要生成缩略图的文件后缀
        //$upload->thumbSuffix = "_thumb";
        //设置缩略图最大宽度
        $upload->uploadReplace = true;
        if (!$upload->upload()) {
            $error = $upload->getErrorMsg();
            return $error;
        } else {
            $uploadList = $upload->getUploadFileInfo();
            return $uploadList;
        }
    }
    //检查验证码
    function check_verify($code, $id = '') {
        import('@.ORG.Verify');
        $verify = new Verify();
        return $verify->check($code, $id);
    }
    //增加一个任务
    public function insert() {
		$formDB = M('Form');
		//验证表单的正确性
		if(isset($_POST['form_id']) && intval($_POST['form_id']) > 0){
			$formS = $formDB -> where(array('id' => intval($_POST['form_id']))) -> find();
		}else{
			$this->error('表单错误！');
			exit();
		}
		//限制提交周期
		if(intval($formS['cycle']) > 0){
			if(S('Mission_cycle')){
				$this->error($formS['cycle'].'只能提交一次！');
                exit();
			}
		}
		//如果标题为空
		if(!isset($_POST['title']) || (isset($_POST['title']) && $_POST['title'] == '')){
			$_POST['title'] = '无标题';
		}
		
		//是否需要登录 
		if($formS['needLogin'] > 0 && !session('memberInfo')){
			$ret['status'] = 0;
			$ret['info'] = '您需要登录后才能提交！';
			$ret['url'] = '';
			$ret['needLogin'] = 1;
			
		    echo json_encode($ret);
			exit;
		}
		
		
		
		
        if (!$this->check_verify($this->_post('verify') , 'mycms') && $formS['needVerify'] > 0) {
            session('mycms','');
            $this->error('验证码错误！');
            exit();
        }
		
        $uploadret = $this->_upload();
        $filekey = 0;
        foreach ($_FILES as $k => $v) {
            $_POST[$k] = $uploadret[$filekey]['savepath'] . $uploadret[$filekey]['savename'];
            $filekey++;
        }
        foreach ($_POST as $k => $v) {
            if (is_array($v)) {
                $_POST[$k] = implode('　　', array_values($v));
            }
        }
        //获取页面提交的所有表单元素的数据集
        $data['object'] = serialize($_POST);
        //流水号
        $data['record'] = build_order_no();
        //任务类型 外部任务
        $data['missionType'] = 1;
        //任务状态 审核中
        $data['state'] = 1;
        //标题
        $data['title'] = $_POST['title'];
        //问题详情
        $data['detail'] = $_POST['detail'];
        //当前表单ID
        $data['form_id'] = $_POST['form_id'];
        //创建任务的时间
        $data['createtime'] = time();
        //当前站点ID
        $data['site_id'] = __SITEID__;
		
		$data['member_id'] = empty($this->memberInfo['id'])?0:intval($this->memberInfo['id']);
        //实例化任务对象
        $Mission = M('Mission');
		$data[C('TOKEN_NAME')] = $_SESSION[C('TOKEN_NAME')];
        //创建任务数据对象
        $cdata = $Mission->create($data);
		if(!$cdata){
			$this->error($Mission -> getError());exit;
		}
        //添加数据
        $mid = $Mission->add();
        if ($mid) {
            
            /*$url = $this->addDimension($mid);
            //遍历会员与用户的关系表 群发微信信息到管理员
            $memberUser = M('member_user');
            $Member = M('member');
            $data = $memberUser->select();
            foreach ($data as $v) {
                $members = $Member->where(array(
                    'id' => $v['member_id']
                ))->find();
                //sendWXMsg($members['openid'], "系统通知：\r\n亲们~现有一条ID为：" . $mid . "，名为" . $_POST['title'] . "的任务等着大家哦，任务详情为\r\n" . $_POST['detail']);
            }*/
			//限制提交周期
			if(intval($formS['cycle']) > 0){
				S('Mission_cycle', 1, $formS['cycle']);
			}
			
            $this->success($formS['successInfo'], $formS['successJumpUrl']);
        }
    }
    public function showqr() {
        $mid = $this->_get('mission_id');
        $Mission = M('mission');
        $data = $Mission->where(array(
            'm.id' => $mid
        ))->alias('m')->join("left join __DIMENSION__ as d on d.id = m.dimension_id")->Field('d.image_url,m.*,m.record')->find();
        $this->assign('mission', $data);
        $this->display();
    }
    //添加二维码  便于发送任务状态信息
    public function addDimension($mid) {
        //调用创建二维码方法 获取到二维码URL
        $url = createDimension('45' . $mid); //在任务ID前面加前缀 0  便于二维码的事件判断它为扫描二维码时产生
        $Dimension = M('dimension');
        $data['image_url'] = $url;
        $did = $Dimension->add($data);
        if ($did) { //保存二维码成功的话 就添加任务表的二维码字段
            $Mission = M('mission');
            $parameter['dimension_id'] = $did;
            $parameter['id'] = $mid; //作用于指定修改的任务信息数据
            $ret = $Mission->save($parameter);
            if ($ret == 1) {
                return $url;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /**
     * 显示任务信息
     */
    public function getMission() {
    }
    //数据的基本操作方法
    public function testCode() {
        //获取操作对象
        $Mission = M('mission');
        //初始化数据
        /*$data['record'] = '123456';
        $data['missionType'] = 0;
        $data['title'] = '552222';
        $Mission -> add($data);//添加数据*/
        //删除数据
        //$Mission -> where('missionType=0') -> delete();
        //更新
        //更新某个字段，如title字段
        $Mission->where('id=3')->setField('title', '1314159');
        //同时更新多个字段
        /* $data = array('title'>='123456','missionType'>=1);
         $missions -> where('id=3') -> setField($data);*/
        //更新方法摘要
        /*setInc('int类型的字段');//值加1
        setInc('int类型的字段',3);//值加3
        setDec('int类型的字段');//值减1
        setDec('int类型的字段',4)//值减4*/
        //查询数据
        $missions = $Mission->select();
        dump($missions);
    }
	
	public function missionList(){
		if(IS_AJAX){
			$this->initView();
			D('Mission')->_list($this->view,['approver'=>['like','%'.session(C('USER_AUTH_KEY')).'%']]);
			$this->display();	
		}
	}
}

